/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.modules.system.auth.cachemanager.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.ksplatform.modules.system.auth.buttonmanager.model.PlatButton;
import cn.com.ksplatform.modules.system.auth.menumanager.model.PlatMenu;
import cn.com.ksplatform.modules.system.auth.resourcemanager.model.PlatResource;
import cn.com.ksplatform.modules.system.auth.rolemanager.model.PlatRole;
import cn.com.ksplatform.modules.system.auth.rolemanager.service.PlatRoleService;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

@Component("system.modules.system.cache.RoleCacheService")
public class RoleCacheService {
	@Autowired
	@Qualifier("cacheManagerFactory")
	CacheManager cacheManager;
	
	@Autowired
	PlatRoleService roleService;
	
	Cache roleCache = null;
	
	public Cache getCache(){
		if(roleCache == null){
			roleCache = cacheManager.getCache("RoleDataCache");
		}
		return roleCache;
	}
	
	
	@Transactional
	public void init(){
		List<PlatRole> roles = roleService.getAllRole();
		for(PlatRole role : roles){
			Set<PlatButton> buttons = role.getBtns(); 
			Set<PlatResource> resources = role.getResources(); 
			Set<PlatMenu> menus = role.getMenus();
			Set menuIds = new HashSet();
			Set btnIds = new HashSet();
			Set resIds = new HashSet();
			for(PlatMenu m : menus){
				menuIds.add(m.getMenuId());
			}
			for(PlatButton button : buttons){
				btnIds.add(button.getBtnId());
			}
			for(PlatResource resource : resources){
				resIds.add(resource.getResourceid());
			}
			Element roleMenus = new Element(role.getRoleId()+"[menus]", menuIds);
			Element roleBtns = new Element(role.getRoleId()+"[btns]", btnIds);
			Element roleRes = new Element(role.getRoleId()+"[res]", resIds);
			getCache().put(roleMenus);
			getCache().put(roleBtns);
			getCache().put(roleRes);
		}
	}
}
